import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { PostRiskScheme, IRiskControlQueryParams } from '@shared/interfaces/post-risk-control'
import { NzMessageService } from 'ng-zorro-antd'
import { I18NService } from '@core'
import { Router, ActivatedRoute } from '@angular/router'
import { ISearchSchema, ISearchOption } from '@shared/interfaces/search'
import { STColumn } from '@delon/abc'
import { SettingsService } from '@delon/theme'
import { ESearchType, EStatus } from '@shared/enums'
import { IAamsItem } from '@shared/components/aams-select/aams-select.interface'
import { PostRiskService } from '../post-risk.service'
import { SchemeStatusTextMap } from '@shared/interfaces/common'
import { ModalService } from '@shared/services/modal.service'
import { Currency } from '@shared/interfaces/common'
import { AAMSFilterInit } from '@shared/interfaces/aams'
import { PostRiskStoreService } from '../new/post-risk-store.service'
import { AcquirerService } from '../../acquirer/acquirer.service'
import { take } from 'rxjs/operators'
import { PageService } from '@shared/services/page.service'
import { SuccessCode, ErrorCode } from '@shared/interfaces/common'

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['../../../shared/styles/table.less'],
})
export class ListComponent extends ListBaseClass<PostRiskScheme, IRiskControlQueryParams>
  implements OnInit, AAMSFilterInit {
  @ViewChild('tplAcquirer') tplAcquirer: TemplateRef<void>
  @ViewChild('tplCurrency') tplCurrency: TemplateRef<void>
  selectedAcquirer: IAamsItem
  selectedCurrency: Currency
  SchemeStatusTextMap = SchemeStatusTextMap
  statusOptions = [
    { label: this.trans('GENERAL.STATUS.NORMAL'), value: '0' },
    { label: this.trans('GENERAL.STATUS.FREEZE'), value: '1' },
  ]

  searchSchema: ISearchSchema[] = []

  customSchema: ISearchSchema[] = []

  data: PostRiskScheme[] = []
  columns: STColumn[] = [
    {
      type: 'link',
      title: '风控方案代码',
      i18n: 'RISK_CTRL.SCHEME_CODE',
      index: 'schemeCode',
      width: '150px',
      className: 'text-center',
      fixed: 'left',
      click: this.goDetail.bind(this),
    },
    {
      title: '风控方案名称',
      i18n: 'RISK_CTRL.SCHEME_NAME',
      index: 'schemeName',
      width: '150px',
      className: 'text-center',
    },
    {
      title: '方案描述',
      i18n: 'RISK_CTRL.SCHEME_DESC',
      index: 'schemeDesc',
      className: 'text-center',
      width: '150px',
      render: 'type',
    },
    {
      title: '更新时间',
      i18n: 'GENERAL.INFO.UPDATED_AT',
      index: 'updatedAt',
      className: 'text-center',
      width: '200px',
      type: 'date',
      dateFormat: 'YYYY-MM-DD HH:mm',
    },
    {
      title: '状态',
      i18n: 'GENERAL.INFO.STATUS',
      index: 'status',
      className: 'text-center',
      width: '100px',
      render: 'status',
    },
    // 操作按钮
    {
      title: '操作',
      width: '150px',
      className: 'text-center p-xs',
      fixed: 'right',
      buttons: [
        {
          text: '',
          click: this.deleteSchemeDialog.bind(this),
          icon: {
            iconfont: 'icon-delete-circle',
            type: 'iconfont',
          },
        },
        {
          text: '',
          click: this.copySchemeDialog.bind(this),
          icon: {
            iconfont: 'icon-copy-circle-twotone',
            type: 'iconfont',
          },
        },
      ],
    },
  ]

  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    public router: Router,
    public route: ActivatedRoute,
    private riskService: PostRiskService,
    private modalService: ModalService,
    public riskStore: PostRiskStoreService,
    public acquirerService: AcquirerService,
    public settings: SettingsService,
    public pageService: PageService,
    public msgSrv: NzMessageService,
  ) {
    super(msg, i18n, route, router, settings)
  }

  ngOnInit() {
    this.initSearchParams()
    this.parseParams().subscribe(() => {
      this.queryTableDataWithParams()
    })
    this.initialAAMSFilter()
  }

  initialAAMSFilter() {
    this.initAcquirer()
  }

  initSearchParams(): void {
    this.searchSchema = [
      {
        label: 'GENERAL.INFO.CREATED_AT',
        labelI18n: 'GENERAL.INFO.CREATED_AT',
        index: ['submittedAtFrom', 'submittedAtTo'],
        type: ESearchType.dateRange,
        value: [],
      },
      {
        label: 'GENERAL.INFO.UPDATED _AT',
        labelI18n: 'GENERAL.INFO.UPDATED_AT',
        index: ['updatedAtFrom', 'updatedAtTo'],
        type: ESearchType.dateRange,
        value: [],
      },
      {
        label: 'ROLE.OWNER_INS TITUTION',
        labelI18n: 'ROLE.OWNER_INSTITUTION',
        index: 'insCode',
        component: this.tplAcquirer,
        customFunc: () => this.selectedAcquirer && this.selectedAcquirer.code,
      },
      {
        label: 'RISK_CTR L.SCHEME_CODE',
        labelI18n: 'RISK_CTRL.SCHEME_CODE',
        index: 'schemeCode',
        type: ESearchType.input,
      },
      {
        label: 'RIS K_CTRL.SCHEME_NAME',
        labelI18n: 'RISK_CTRL.SCHEME_NAME',
        index: 'schemeName',
        type: ESearchType.input,
      },
      {
        label: 'GENERAL.INFO.TRANSACTION_CURRENCY',
        labelI18n: 'GENERAL.INFO.TRANSACTION_CURRENCY',
        index: 'currency',
        component: this.tplCurrency,
        customFunc: () => this.selectedCurrency && this.selectedCurrency.code,
      },
      {
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        index: 'status',
        type: ESearchType.selection,
        options: [
          { label: this.trans('GENERAL.STATUS.NORMAL'), value: '0' },
          { label: this.trans('GENERAL.STATUS.FREEZE'), value: '1' },
        ],
      },
    ]
  }

  goAdd(): void {
    this.router.navigate(['postRisk/creatRiskScheme/new'])
  }

  goDetail(scheme: PostRiskScheme): void {
    const { schemeCode } = scheme
    this.router.navigate([`../${schemeCode}`], { relativeTo: this.route })
  }
  deleteSchemeDialog(record: PostRiskScheme): void {
    const { schemeCode, schemeName } = record
    const msg = this.trans('GENERAL.NOTIFICATION.DELETE_CONFIRM', { schemeName })
    this.modalService.delete(msg).subscribe(isOk => {
      if (!isOk) return
      this.delete(schemeCode)
    })
  }

  delete(schemeCode: string): void {
    this.riskService.delete(schemeCode).subscribe(() => {
      this.queryTableDataWithParams()
    })
  }

  copySchemeDialog(record: PostRiskScheme) {
    // 复制方案 存储一下方案数据 TODO
    this.acquirerService
      .getOne(record.insCode as string)
      .pipe(take(1))
      .subscribe(data => {
        record.insCode = {
          code: data.institution.common.insCode,
          num: data.institution.common.insCode,
          level: 'institution',
          nameEN: data.institution.common.insNameEN,
          name: data.institution.common.insName,
        }
        this.riskStore.setValue(record)
        this.router.navigate(['postRisk/creatRiskScheme/new'], { queryParams: { type: 1 } })
      })
  }

  renderList(res): void {
    const { data, total } = res
    this.data = data || []
    this.total = total
    this.loading = false
  }

  // 查询列表数据
  queryTableDataWithParams(): void {
    this.loading = true
    this.riskService.getList(this.params).subscribe(this.renderList.bind(this), this.getListError.bind(this))
  }
}
